const express = require('express');
const router = express.Router();

router.get('/orgs', async (req, res, next) => {
    const locale = req.query.locale || 'zh-cn'; 

    const dictModel = res.app.models['dictionary'];
    if (!dictModel) {
        return next('route');
    }
    const nodes = await dictModel.find({ 
        Enabled: true,
        Name: '标准技术委员会',
    }, {
        id: 1,
        Index: 1,
        Labels: 1,
        Value: 1,
        Parent: 1,
    }).lean();

    const allNodes = {};
    const retTree = [];

    for (let i = 0; i < nodes.length; i += 1) {
        const node = nodes[i];

        node.Label = (node.Labels || []).find((item) => item.Locale === locale) || {};
        const Description = node.Label && node.Label.Description && node.Label.Description.split('|');
        node.Name = Description && Description[0] || '';
        node.Description = Description && Description[1] || '';
        node.Label = node.Label && node.Label.Label;
        
        delete node.Value;
        delete node.Labels;

        allNodes[node.id] = node;
        delete node._id;
        node.children = [];
        if (!node.Parent) {
            retTree.push(node);
        }
    }

    for (let i = 0; i < nodes.length; i += 1) {
        const node = nodes[i];
        if (node.Parent) {
            const parent = allNodes[node.Parent];
            if (parent) {
                if (parent.Parent) {
                    node.Label = `${parent.Label}/${node.Label}`;
                }
                parent.children.push(node);
                // delete node.Parent;
                parent.children = parent.children.sort((a, b) => a.Index - b.Index);
            }
        }
    }

    res.locals.data = (retTree[0] && retTree[0].children) || [];

    return next();
});

// api to add new '意见批次'
router.post('/comment/batch/:id', 
    async (req, res, next) => {
        const newBatch = `${req.body.batch}`.trim();
        if (!req.params.id || !newBatch) {
            return next('route');
        }

        const theStd = await res.app.models.standards_in_dev.findOne({
            id: req.params.id,
        }, {
            意见批次: 1,
        }).lean();

        if (!theStd) {
            res.makeError(402, 'The standard does not exist', router.mdl);
            return next('route');
        }

        // cannot add the existing batch
        if (theStd.意见批次 && (theStd.意见批次 === newBatch)) {
            res.makeError(403, 'The batch already exists', router.mdl);
            return next('route');
        }

        const existsBatchs = await res.app.models.forum_comments.distinct('批次', {
            Board: 'stddev',
            Topic: req.params.id,
        });
        if (theStd.意见批次 && existsBatchs.includes(newBatch)) {
            res.makeError(403, 'The batch already exists', router.mdl);
            return next('route');
        }

        await res.app.models.standards_in_dev.updateOne({
            id: req.params.id,
        }, {
            $set: {
                意见批次: newBatch,
            },
        });

        // if theStd.意见批次 is null, then update all comments to new batch
        if (!theStd.意见批次) {
            await res.app.models.forum_comments.updateMany({
                Board: 'stddev',
                Topic: req.params.id,
            }, {
                $set: {
                    批次: newBatch,
                },
            });
        }

        res.locals.data = {};
        return next();
    }
);

// update '意见批次' to new name
router.put('/comment/batch/:id',
    async (req, res, next) => {
        if (!req.params.id || !req.body.batch) {
            return next('route');
        }
        const theStd = await res.app.models.standards_in_dev.findOne({
            id: req.params.id,
        }, {
            意见批次: 1,
        }).lean();

        if (!theStd) {
            res.makeError(402, 'The standard does not exist', router.mdl);
            return next('route');
        }

        const currentBatch = theStd.意见批次 || '默认批';

        await res.app.models.standards_in_dev.updateOne({
            id: req.params.id,
        }, {
            $set: {
                意见批次: `${req.body.batch}`.trim(),
            },
        });

        await res.app.models.forum_comments.updateMany({
            批次: currentBatch,
        }, {
            $set: {
                批次: `${req.body.batch}`.trim(),
            },
        });

        res.locals.data = {};
        return next();
    }
);

module.exports = router;
